package org.management.config.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.management.config.shiro.manager.TokenManager;

/**
 * @title: SystemFilter
 * @description: session超时 过滤器
 * @author: jiangyan
 * @date:  2019/1/24
 */
public class SystemFilter extends AccessControlFilter{

	@Override
	protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object arg2) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		//判断session里是否有用户信息
		if (!SecurityUtils.getSubject().isAuthenticated()) {
			if (request.getHeader("x-requested-with") != null
					&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
				//如果是ajax请求响应头会有，x-requested-with
				//在响应头设置session状态
				response.setHeader("sessionStatus", "timeout");
				TokenManager.logout();
				return false;
			}
			return false;
		}
		return true;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest arg0, ServletResponse arg1)  {
		return false;
	}

}
